<template>
  <div class="init_upload" ref="uploadRef" style="overflow:hidden;">
    <el-upload
        v-model:file-list="files"
        :style="uploaderStyle"
        :show-file-list="false"
        :auto-upload="false"
        :before-upload="beforeAvatarUpload"
        :on-change="handleChange"

    >
      <template #trigger>
        <el-icon  v-if="!pictureUrl ||pictureUrl === ''">
          <Plus/>
        </el-icon>
        <el-image  v-if="pictureUrl && pictureUrl != ''" :src="pictureUrl" :fit="fill"></el-image>
      </template>
    </el-upload>

</div>

</template>

<script setup lang="ts">
import {ElIcon, ElMessage} from "element-plus";
import { onMounted, ref} from "vue";
import {batchUploadSelf} from "@/api/modules/system/upload";

let props = defineProps({
  height: Number,
  width: Number,
  initUrl: String
});

let files = ref()
let open = ref(true)
let uploadRef = ref()
let fill = ref('fill')
let pictureUrl = ref( props.initUrl)



/**
 * 这里handleChange的file是逐个执行的
 * @param file
 */
let handleChange = (uploadFile1: any, uploadFiles1: any) => {
  console.log('触发了', uploadFile1,uploadFiles1)
  open.value = false;

  batchUploadSelf({uploadSelfs: [uploadFile1.raw]}).then(res =>{
    console.log('触发了', res)
    if (res.data && res.data?.length > 0){
      pictureUrl.value =res.data[0].url
    }
  });
}

let uploaderStyle = () => {
  console.log('chufadfasdfasdf')
  return {
    height: `${props.height}px`,
    width: `${props.width}px`,
  }
}
onMounted(()=>{
    uploadRef.value.style.height = props.height+'px'
    uploadRef.value.style.width = props.width+'px'
})


let beforeAvatarUpload = (rawFile: any) => {
  const isImage = rawFile.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片类型文件');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 100) {
    ElMessage.error('图片大小不能超过100M');
    return false;
  }
  return true;
}


defineExpose({pictureUrl})

</script>


<style scoped>

.init_upload {
  position: relative;
  height: 100%; /* 确保容器高度为100% */
  width: 100%; /* 确保容器宽度为100% */
  display: flex; /* 添加 flex 布局 */
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload {
  width: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 100%; /* 强制 el-upload 占满父容器 */
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}


</style>